#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import tarfile

from django.conf import settings
from django.conf.urls import url
from django.http import HttpResponse
from django.template import loader

from ManageDaemon.DownLoad import *
from ManageDaemon.settings import REPOSITORY_JAVA_TEMP
from ManageDaemon.view import TailLog
from ManageDaemon.view.Base import getActionSession
from ManageDaemon.view.ResultModel import ResultModel
from utils import Logger
from utils.ActionSession import createActionSession, updateActionSession
from utils.Md5Utils import getFileMd5
from utils.MyJsonResponse import MyJsonResponse, errorResponse, errorDaemon, successResponse

logger = Logger.Logger().getLogger()


def urls():
    urlpatterns = [
        url(r'^$', Index),
        url(r'^download/', download),
        url(r'^downloadProgressRate/', downloadProgressRate),
        url(r'^install/', install),
        url(r'^server/install/', serverInstall),
        url(r'^server/appConfigure/', appConfigure),
        url(r'^server/updatePackageApplication/', updatePackageApplication),
        url(r'^server/startApplication/', startApplication),
        url(r'^server/restartApplication/', restartApplication),
        url(r'^server/stopApplication/', stopApplication),
        url(r'^server/testTime/', testTime),
        url(r'^tailLog/list', tailLogList),
        url(r'^server/serverPathApplication/', serverPathApplication),

    ]
    return urlpatterns, 'java', 'java'


def downloadProgressRate(request):
    resultModel = ResultModel()
    filePath = getActionSession(request)
    if not os.path.exists(filePath["filePath"]):
        return errorResponse("文件不存在")
    fileSize = os.path.getsize(filePath["filePath"])
    print(filePath)
    if fileSize == filePath["ariaValuemax"]:
        # 还要解压,先不删除
        # del download_[id]
        # logger.debug("md5=%s,fileMd5=%s", REPOSITORY_JAVA_JDK11["md5"], getFileMd5(filePath["filePath"]))
        if filePath["md5"].lower() != getFileMd5(filePath["filePath"]).lower():
            resultModel.status = 1
            resultModel.message = "文件md5验证失败"
            return MyJsonResponse(resultModel.__dict__)
        resultModel.status = 0
    else:
        resultModel.status = 8
    resultModel.data = {"filePath": filePath["filePath"],
                        "fileSize": fileSize,
                        "ariaValuemax": filePath["ariaValuemax"]
                        }
    return MyJsonResponse(resultModel.__dict__, safe=False)


def download(request):
    print("----------request.body")
    print(type(request.body))

    if len(request.body) == 0:
        return errorResponse("request.body无数据")


    REPOSITORY_JAVA_JDK11 = json.loads(request.body)
    resultModel = ResultModel()
    resultModel.message = ""
    if REPOSITORY_JAVA_TEMP is None:
        resultModel.status = 1
        resultModel.message = "repository.java.temp 配置属性不存在"
        return MyJsonResponse(resultModel.__dict__)
    if REPOSITORY_JAVA_JDK11 is None:
        resultModel.status = 1
        resultModel.message = "repository.java.jdk11 配置属性不存在"
        return MyJsonResponse(resultModel.__dict__)

    uuidStr = createActionSession({})

    name_ = REPOSITORY_JAVA_JDK11["name"]
    savePath = os.path.join(REPOSITORY_JAVA_TEMP, name_)
    urlStr = REPOSITORY_JAVA_JDK11["url"]


    downloadB=True;
    if os.path.exists(savePath):
        if REPOSITORY_JAVA_JDK11["md5"].lower() == getFileMd5(savePath).lower():
            # 文件存在,md5也相同,则不再下载
            downloadB=False;
            content_size=getContentSize(urlStr)

    if downloadB:
        content_size = newDownload(urlStr, savePath)
    resultModel.data = {"ariaValuemax": content_size, "id": uuidStr}

    sessionDict = {"filePath": savePath,
                   "ariaValuemax": content_size,
                   "url": urlStr,
                   "md5": REPOSITORY_JAVA_JDK11["md5"]
                   }
    #合并字典,相同的key会以sessionDict 为最终结果
    sessionDict={**REPOSITORY_JAVA_JDK11,**sessionDict}
    print(sessionDict)
    updateActionSession(uuidStr, sessionDict)
    logger.debug("download=%s", str(sessionDict))
    # json.dumps方法不能对自定义对象直接序列化,首先把自定义对象转换成字典
    return MyJsonResponse(resultModel.__dict__)


def install(request):
    resultModel = ResultModel()
    actionSession = getActionSession(request)

    serverJava = getattr(settings, 'SERVER_JAVA')
    jdkPath=serverJava["jdkPath"]
    fileType=actionSession["fileType"]
    filePath=actionSession["filePath"]


    if os.path.exists(jdkPath+"/"+actionSession["pathName"]):
        return errorDaemon("已安装")

    if fileType == "tar.gz":
        t = tarfile.open(filePath)
        t.extractall(path=jdkPath)
        return MyJsonResponse(resultModel.__dict__)

    return errorDaemon("未定义该类型的安装方式")

def Index(request):
    name = request.GET.get("server_name")
    if name == None or name == '':
        return HttpResponse("server_name 参数不能为空")
    print("name=%s" % (name))
    content = loader.render_to_string('java/java-server.sh', {'server_name': name})
    print(content)
    # return render_to_response("a.html",{'name':"asus"})
    return HttpResponse(content)


def serverInstall(request):
    if len(request.body) == 0:
        return errorResponse("request.body无数据")

    serverJava = getattr(settings, 'SERVER_JAVA')
    if not os.path.exists(serverJava["serversPath"]):
        return errorDaemon("服务器中java服务安装目录不存在")
    d = json.loads(request.body)
    application = d["application"]
    repository = d["repository"]
    workPath=os.path.join(serverJava['serversPath'], application["serverPath"])
    # if os.path.exists(pathTemp):
    #     return errorDaemon("服务器中服务已经安装")
    # 创建目录
    if not os.path.exists(workPath):
        os.mkdir(workPath)
    if not os.path.exists(workPath+"/logs"):
        os.mkdir(workPath+"/logs")

    # 下载jar
    jarSavePath=os.path.join(workPath, application["packageName"])

    if not os.path.exists(jarSavePath):
        try:
            newDownload(application["packageUrl"], jarSavePath)
        except Exception as err:
            print(str(err))

    javaHomePath=os.path.join(serverJava["jdkPath"], repository["pathName"])
    if not os.path.exists(javaHomePath):
        return errorDaemon("jdk未安装")

    if "daemonKey" not in application.keys():
        return errorDaemon("未设置应用daemonKey")

    #保存shell脚本
    content = loader.render_to_string('java/java-server.sh', {'server_name': application["serverName"],
                                                              "jar_path":jarSavePath,
                                                              "work_path":workPath,
                                                              "java_home":javaHomePath,
                                                              "packageUrl":application["packageUrl"],
                                                              "appKey":application["daemonKey"],
                                                              "appId":application["quitterApplicationId"],
                                                              "daemonQuitterUrl":d["daemonQuitterUrl"]
                                                              })
    # print(content)
    shellSavePath=os.path.join(workPath,application["serverPath"])
    f = open(shellSavePath, 'w')
    f.write(content)
    f.close()



    os.chmod(shellSavePath, 0o0754)


    return errorDaemon("安装完成")


def appConfigure(request):
    if len(request.body) == 0:
        return errorResponse("request.body无数据")
    serverJava = getattr(settings, 'SERVER_JAVA')
    if not os.path.exists(serverJava["serversPath"]):
        return errorDaemon("服务器中java服务安装目录不存在")
    d = json.loads(request.body)
    application = d["application"]
    repository = d["repository"]
    workPath=os.path.join(serverJava['serversPath'], application["serverPath"])

    if not os.path.exists(workPath):
        return errorDaemon("应用服务未安装")
    applicationYmlPath=os.path.join(workPath, "application.yml")


    applicationContent=""
    if "appConfigure" in application.keys():
        applicationContent=application["appConfigure"]

    f = open(applicationYmlPath, 'w')
    f.write(applicationContent)
    f.close()
    return errorDaemon("配置已更新")

def updatePackageApplication(request):
    if len(request.body) == 0:
        return errorResponse("request.body无数据")
    serverJava = getattr(settings, 'SERVER_JAVA')
    if not os.path.exists(serverJava["serversPath"]):
        return errorDaemon("服务器中java服务安装目录不存在")
    d = json.loads(request.body)
    application = d["application"]
    repository = d["repository"]
    workPath=os.path.join(serverJava['serversPath'], application["serverPath"])

    if not os.path.exists(workPath):
        return errorDaemon("应用服务未安装")
    shellSavePath=os.path.join(workPath,application["serverPath"])
    if not os.path.exists(shellSavePath):
        return errorDaemon("应用服务未安装")
    applicationYmlPath=os.path.join(workPath, "application.yml")
    if not os.path.exists(applicationYmlPath):
        return errorDaemon("应用配置未推送")

    cmdStr= ("%s update" % (shellSavePath))
    print("cmdStr=%s" %(cmdStr))
    outTemp=os.popen(cmdStr)
    read = outTemp.read()
    print(read)
    return successResponse("包更新成功", data=read)

def startApplication(request):
    if len(request.body) == 0:
        return errorResponse("request.body无数据")
    serverJava = getattr(settings, 'SERVER_JAVA')
    if not os.path.exists(serverJava["serversPath"]):
        return errorDaemon("服务器中java服务安装目录不存在")
    d = json.loads(request.body)
    application = d["application"]
    repository = d["repository"]
    workPath=os.path.join(serverJava['serversPath'], application["serverPath"])

    if not os.path.exists(workPath):
        return errorDaemon("应用服务未安装")
    shellSavePath=os.path.join(workPath,application["serverPath"])
    if not os.path.exists(shellSavePath):
        return errorDaemon("应用服务未安装")
    applicationYmlPath=os.path.join(workPath, "application.yml")
    if not os.path.exists(applicationYmlPath):
        return errorDaemon("应用配置未推送")

    cmdStr= ("%s start" % (shellSavePath))
    print("cmdStr=%s" %(cmdStr))
    outTemp=os.popen(cmdStr)
    read = outTemp.read()
    print(read)
    return successResponse("服务启动成功", data=read)

def serverPathApplication(request):
    if len(request.body) == 0:
        return errorResponse("request.body无数据")
    serverJava = getattr(settings, 'SERVER_JAVA')
    if not os.path.exists(serverJava["serversPath"]):
        return errorDaemon("服务器中java服务安装目录不存在")
    d = json.loads(request.body)
    application = d["application"]
    workPath=os.path.join(serverJava['serversPath'], application["serverPath"])
    if not os.path.exists(workPath):
        return errorDaemon("应用服务未安装")
    return successResponse("服务重启成功", data=workPath)

def restartApplication(request):
    if len(request.body) == 0:
        return errorResponse("request.body无数据")
    serverJava = getattr(settings, 'SERVER_JAVA')
    if not os.path.exists(serverJava["serversPath"]):
        return errorDaemon("服务器中java服务安装目录不存在")
    d = json.loads(request.body)
    application = d["application"]
    repository = d["repository"]
    workPath=os.path.join(serverJava['serversPath'], application["serverPath"])

    if not os.path.exists(workPath):
        return errorDaemon("应用服务未安装")
    shellSavePath=os.path.join(workPath,application["serverPath"])
    if not os.path.exists(shellSavePath):
        return errorDaemon("应用服务未安装")
    applicationYmlPath=os.path.join(workPath, "application.yml")
    if not os.path.exists(applicationYmlPath):
        return errorDaemon("应用配置未推送")

    cmdStr= ("%s restart" % (shellSavePath))
    print("cmdStr=%s" %(cmdStr))
    outTemp=os.popen(cmdStr)
    read = outTemp.read()
    print(read)
    return successResponse("服务重启成功", data=read)


def stopApplication(request):
    if len(request.body) == 0:
        return errorResponse("request.body无数据")
    serverJava = getattr(settings, 'SERVER_JAVA')
    if not os.path.exists(serverJava["serversPath"]):
        return errorDaemon("服务器中java服务安装目录不存在")
    d = json.loads(request.body)
    application = d["application"]
    repository = d["repository"]
    workPath=os.path.join(serverJava['serversPath'], application["serverPath"])

    if not os.path.exists(workPath):
        return errorDaemon("应用服务未安装")
    shellSavePath=os.path.join(workPath,application["serverPath"])
    if not os.path.exists(shellSavePath):
        return errorDaemon("应用服务未安装")
    applicationYmlPath=os.path.join(workPath, "application.yml")
    if not os.path.exists(applicationYmlPath):
        return errorDaemon("应用配置未推送")

    cmdStr= ("%s stop" % (shellSavePath))
    print("cmdStr=%s" %(cmdStr))
    outTemp=os.popen(cmdStr)
    read = outTemp.read()
    print(read)
    return successResponse("服务停止成功", data=read)


def testTime(request):

    data="";

    cmdStr= ("date" )
    print("cmdStr=%s" %(cmdStr))
    outTemp=os.popen(cmdStr)
    read = outTemp.read()
    data=data+read+"\n"
    print(read)
    # cmdStr= ("timedatectl" )
    # print("cmdStr=%s" %(cmdStr))
    # outTemp=os.popen(cmdStr)
    print("111a")
    # read = outTemp.read()
    # data=data+read
    print("111b")
    print(read)
    print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
    print("111c")
    return successResponse("服务启动成功",data=data)


def tailLogList(request):
    if len(request.body) == 0:
        return errorResponse("request.body无数据")

    serverJava = getattr(settings, 'SERVER_JAVA')
    if not os.path.exists(serverJava["serversPath"]):
        return errorDaemon("服务器中java服务安装目录不存在")
    d = json.loads(request.body)
    application = d["application"]
    repository = d["repository"]

    workPath=os.path.join(serverJava['serversPath'], application["serverPath"])
    if not os.path.exists(workPath):
        return errorDaemon("不存在该目录")

    return TailLog.listFile(request,workPath)